﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using MySqlStudent.UI.Models;
using System.Collections.Generic;

namespace MySqlStudent.UI.Repo
{
    public class StudentRepository : IStudentRepository
    {
        private readonly ef_mysql_demoContext _context;
        private readonly ILogger<StudentRepository> _logger;

        public StudentRepository(ef_mysql_demoContext context,
            ILogger<StudentRepository> logger)
        {
            _context = context;
            _logger = logger;
        }

        public Student delete(int id)
        {
            Student student = _context.Students.Find(id);
            if (student != null)
            {
                _context.Students.Remove(student);
                _context.SaveChanges();
            }

            return student;
        }

        public IEnumerable<Student> GetAllStudents()
        {
            _logger.LogTrace("学生信息Trace(跟踪)Log");
            _logger.LogDebug("学生信息Debug(调试)Log");
            _logger.LogInformation("学生信息 信息(Information)Log");
            _logger.LogWarning("学生信息 警告(Warning)Log");
            _logger.LogError("学生信息 错误(Error)Log");
            _logger.LogCritical("学生信息 严重 (Critical) Log");

            return _context.Students;
        }

        public Student GetStudentId(int id)
        {
            return _context.Students.Find(id);
        }

        public Student Insert(Student student)
        {
            _context.Students.Add(student);
            _context.SaveChanges();
            return student;
        }

        public Student Update(Student upStudent)
        {
            var student = _context.Students.Attach(upStudent);
            student.State = EntityState.Modified;
            _context.SaveChanges();
            return upStudent;
        }
    }
}